package com.etoak.controller;


import com.etoak.bean.Movie;
import com.etoak.service.MovieService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/movie")
@Controller
@Slf4j
public class MovieController {

    @Autowired
    MovieService movieService;

    @GetMapping("/toadd")
    public String toAdd(){
        System.out.println("我进来了");
        return "/index";
    }

    @PostMapping("/add")
    public String addMovie(MultipartFile file, Movie movie, Model model){

        log.info("movie -{}",movie);
        long size = file .getSize();
        if(size<=0) {
            model.addAttribute("erroe","请上传图片");
            return "forward:/toadd";
        }
        String oldFileName = file.getOriginalFilename();

        String suffix = FilenameUtils.getExtension(oldFileName);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String newName = uuid+"."+suffix;

        File uploadDir = new File("d:/upload");
        if(!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        File destFile = new File(uploadDir,newName);

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String savePath = "/pic/"+newName;

        movie.setPic(savePath);
        int x = movieService.addMovie(movie);
        return "/index";

    }
}
